package ar.edu.itba.it.pdc.httpParser.models;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.Queue;

import ar.edu.itba.it.pdc.httpParser.interfaces.Model;
import ar.edu.itba.it.pdc.nio.ByteBufferPool;
import ar.edu.itba.it.pdc.nio.MemoryAllocationLimitHited;

public class HttpStatusLine implements Model {


	private Token statusCode;

	private List<Token> statusDesc;

	private HttpVersion version = null;
	
	ByteBuffer byteBuffer;
	
	public void setStatusCode(Token statusCode) {
		this.statusCode = statusCode;
	}

	public void setStatusDesc(List<Token> statusDesc) {
		this.statusDesc = statusDesc;
	}

	public void setVersion(HttpVersion version) {
		this.version = version;
	}

	private void add(Queue<ByteBuffer> queue, byte b) throws MemoryAllocationLimitHited {
		byteBuffer.put(b);
		if (byteBuffer.remaining() == 0) {
			byteBuffer.flip();
			queue.add(byteBuffer);
			byteBuffer = ByteBufferPool.getInstance().getByteBuffer();
		}
	}

	public void appendByteBuffers(Queue<ByteBuffer> queue) throws MemoryAllocationLimitHited {
		if(byteBuffer == null)
			byteBuffer = ByteBufferPool.getInstance().getByteBuffer();

		add(queue, (byte)'H');
		add(queue, (byte)'T');
		add(queue, (byte)'T');
		add(queue, (byte)'P');
		add(queue, (byte)'/');

		for (byte b : version.toString().getBytes()) {
			add(queue, b);
		}

		add(queue, (byte)' ');

		for (byte b : statusCode.getName()) {
			add(queue, b);
		}

		add(queue, (byte)' ');

		for (Token token : statusDesc) {
			for (Byte b : token.getName()) {
				add(queue, b);
			}
		}

		add(queue, (byte)'\r');
		add(queue, (byte)'\n');
		

		if (byteBuffer.position() != 0) {
			byteBuffer.flip();
			queue.add(byteBuffer);
			byteBuffer = null;
		}
	}
	
	public HttpVersion getVersion() {
		return version;
	}
	
	public int getStatusCode(){
		return Integer.parseInt(statusCode.toString());
	}
	
	public String getStatusDesc() {
		String s = "";
		for(Token t: statusDesc) {
			s += t.toString();
		}
		return s;
	}
	
}
